package sy.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sy.dao.TraceDaoI;
import sy.dao.TransportDaoI;
import sy.model.Ttrace;
import sy.model.Ttransport;
import sy.pageModel.DataGrid;
import sy.pageModel.PageHelper;
import sy.pageModel.Trace;
import sy.service.TraceServiceI;

import java.util.*;


@Service("traceService")
public class TraceServiceImpl implements TraceServiceI {
	@Autowired
	private TraceDaoI traceDao;
	@Autowired
	private TransportDaoI transportDao;

	@Override
	public DataGrid dataGrid(Trace trace, PageHelper ph) {

		DataGrid dg = new DataGrid();
		List<Trace> ul = new ArrayList<Trace>();
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from Ttrace t ";
		List<Ttrace> l = traceDao.find(hql + whereHql(trace, params) + orderHql(ph), params, ph.getPage(), ph.getRows());
		if (l != null && l.size() > 0) {
			for (Ttrace t : l) {
				Trace u = new Trace();
				BeanUtils.copyProperties(t, u);
				u.setTransportId(t.getTransport().getId());
				ul.add(u);
			}
		}
		dg.setRows(ul);
		dg.setTotal(traceDao.count("select count(*) " + hql + whereHql(trace, params), params));
		return dg;
	}

	private String whereHql(Trace trace, Map<String, Object> params) {
		String hql = "";
		if (trace != null) {
			hql += " where 1=1 ";
			if(trace.getTransportId() != null && !trace.getTransportId().equals("")){
				hql += " and t.transport.id = :transportId";
				params.put("transportId",trace.getTransportId());
			}
		}
		return hql;
	}

	private String orderHql(PageHelper ph) {
		String orderString = "";
		if (ph.getSort() != null && ph.getOrder() != null) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;


	}

	@Override
	public void add(Trace trace) {
		if (trace.getTransportIds() != null && !"".equals(trace.getTransportIds())) {
			for (String id : trace.getTransportIds().split(",")) {
				if (!id.trim().equals("0")) {
					Ttransport retransportid = transportDao.get(Ttransport.class, id.trim());
					if(retransportid!=null){
						Ttrace ttrace = new Ttrace();
						ttrace.setId(UUID.randomUUID().toString());	
						ttrace.setCreater(trace.getCreater());
						ttrace.setCreateTime(new Date());
						ttrace.setRemark(trace.getRemark());
						if(trace.getTraceTime()!=null){
							ttrace.setTraceTime(trace.getTraceTime());
						}else{
							ttrace.setTraceTime(new Date());
						}
						ttrace.setTransport(retransportid);
						traceDao.save(ttrace);
					}

				}
			}
		}
	}
	@Override
	public void delete(String id){
		traceDao.delete(traceDao.get(Ttrace.class,id));
	}
}

